﻿using ProjectCloth.Entity;
using ProjectCloth.Entity.Enum;
using ProjectCloth.FrmUI.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectCloth.FrmUI
{
    public partial class SaleOrderListFrm : UserControl
    {
        private ClothContext db = new ClothContext();
        private bool IsReturnSearch = false;
        public SaleOrderListFrm(bool isReturnSearch = false)
        {
            InitializeComponent();
            IsReturnSearch = isReturnSearch;
            dataGdv.AutoGenerateColumns = false;
            userCombobox.DataSource = db.Users.Where(o => o.Enabled == true).ToList();
            userCombobox.DisplayMember = "Name";
            userCombobox.ValueMember = "Id";
            userCombobox.SelectedValue = 0;
            var selectList = new List<DataItemStatus>();
            selectList.Add(new DataItemStatus()
            {
                Id = 0,
                Name = "未支付"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 1,
                Name = "已支付"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 3,
                Name = "已审核"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 2,
                Name = "作废"
            });
            selectList.Add(new DataItemStatus()
            {
                Id = 4,
                Name = "已退货"
            });
            var selectList1 = new List<DataItemStatus>();
            selectList1.Add(new DataItemStatus()
            {
                Id = 0,
                Name = "未处理"
            });
            selectList1.Add(new DataItemStatus()
            {
                Id = 1,
                Name = "进行中"
            });
            selectList1.Add(new DataItemStatus()
            {
                Id = 2,
                Name = "已完成"
            });
            //selectList.Add(new DataItemStatus()
            //{
            //    Id = 3,
            //    Name = "作废"
            //});
            statusCombobox.DataSource = selectList;
            statusCombobox.DisplayMember = "Name";
            statusCombobox.ValueMember = "Id";
            statusCombobox.SelectedValue = -1;
            instockStatusCbb.DataSource = selectList1;
            instockStatusCbb.DisplayMember = "Name";
            instockStatusCbb.ValueMember = "Id";
            instockStatusCbb.SelectedValue = -1;
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            var accountList = db.CashAccounts.ToList();
            var startTime = startDatePiker.Value.Date;
            var endTime = endDatePicker.Value.AddDays(1).Date;
            var userId = Convert.ToInt32(userCombobox.SelectedValue);
            var orderNo = orderNoTxt.Text.Trim().ToUpper();
            var status = Convert.ToInt32(statusCombobox.SelectedValue == null ? -1 : statusCombobox.SelectedValue);
            var instockStatus = Convert.ToInt32(instockStatusCbb.SelectedValue == null ? -1 : instockStatusCbb.SelectedValue);
            var summary = summaryTxt.Text;
            var remark = RemarkTxt.Text;
            var CompanyName = CompanyNameTxt.Text;
            var Phone = PhoneTxt.Text;
            var liaison = LiaisonTxt.Text;
            var list = (from o in db.SaleOrders.AsNoTracking().ToList()
                            //join p in db.CashAccounts.ToList() on o.InMoneyAccountId equals p.Id
                        where ((o.RecordDate > startTime && o.RecordDate < endTime) && (o.MakerId == userId || userId <= 0)
                        && (o.OrderStatus == status || status < 0) && (orderNo == "" || o.OrderNo.Contains(orderNo))
                        && (summary == "" || o.Summary.Contains(summary)) && (remark == "" || o.Remark.Contains(remark))
                        && (o.OrderStatus != (int)OrderStatus.Delete) && (instockStatus < 0 || o.Status == instockStatus))
                        && ((IsReturnSearch && o.OrderNo.EndsWith("T")) || (!IsReturnSearch && !o.OrderNo.EndsWith("T")))
                        &&(string.IsNullOrEmpty(CompanyName)||(o.CompanyName!=null&&o.CompanyName.Contains(CompanyName)))
                        &&(string.IsNullOrEmpty(Phone)||(o.Phone!=null&&o.Phone.Contains(Phone)))
                        &&(string.IsNullOrEmpty(liaison)||(o.Liaison!=null&&o.Liaison.Contains(liaison)))
                        select new
                        {
                            o.Liaison,
                            o.OrderNo,
                            o.Summary,
                            o.MakerName,
                            o.Remark,
                            PayType = o.OrderStatus != (int)OrderStatus.Unpay ? o.InMoneyAccountId <= 0 ? "" : (accountList.Where(s => s.Id == o.InMoneyAccountId).Select(s => s.TradeTypeName).FirstOrDefault()) : "",
                            Status = EnumDefine.GetEnumDescription((OrderStatus)o.OrderStatus),
                            InstockStatus = EnumDefine.GetEnumDescription((Status)o.Status),
                        }
                         ).ToList();
            dataGdv.DataSource = list;
            //dataGdv.Refresh();

        }
        private void dataGdv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGdv_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void dataGdv_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var main = MainFrm.CreateInstrance();
                var tab = main.Controls.Find("tabControl1", true).FirstOrDefault() as TabControl;
                var tabControl = tab;
                if (tab != null)
                {
                    tabControl = (TabControl)tab as TabControl;
                }
                if (dataGdv.Rows[e.RowIndex].Cells["OrderNo"].Value == null) return;
                var orderNo = dataGdv.Rows[e.RowIndex].Cells["OrderNo"].Value.ToString();
                if (orderNo.EndsWith("T"))
                    new AddTab(new ReturnSaleOrderFrm(orderNo), "ReturnSaleOrderFrmSearch", "销售单退货查询", tabControl);
                else
                    new AddTab(new SaleOrderFrm(orderNo), "SaleOrderFrmSearch", "销售单查询", tabControl);
            }
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            var isSel = dataGdv.CurrentRow == null ? false : dataGdv.CurrentRow.Selected;
            if (isSel)
            {
                var rowIndex = dataGdv.CurrentRow.Index;
                if (rowIndex >= 0)
                {
                    var dr = MessageBox.Show("确定要作废该订单吗？", "操作提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.OK)
                    {
                        if (dataGdv.CurrentRow.Cells["OrderNo"] != null)
                        {
                            var orderNo = dataGdv.CurrentRow.Cells["OrderNo"].Value.ToString();
                            var order = db.SaleOrders.FirstOrDefault(o => o.OrderNo == orderNo);
                            if (order == null)
                            {
                                MessageBox.Show("订单不存在！");
                                return;
                            }
                            if (order.OrderStatus == (int)OrderStatus.Checked)
                            {
                                MessageBox.Show("已经审核订单不能作废！");
                                return;
                            }
                            if (order.OrderStatus == (int)OrderStatus.Unpay && order.Status == (int)Entity.Enum.Status.Undo)
                            {
                                order.OrderStatus = (int)OrderStatus.Delete;
                                //db.SaleOrders.Attach(order);
                                //db.Entry(order).State = System.Data.Entity.EntityState.Modified;
                                var result = db.SaveChanges();
                                if (result > 0)
                                {
                                    MessageBox.Show("作废订单成功！单号：" + order.OrderNo);
                                    searchBtn_Click(null, null);
                                }
                                else
                                    MessageBox.Show("作废订单失败！");
                            }
                            else if (order.OrderStatus == (int)OrderStatus.Pay && order.Status == (int)Entity.Enum.Status.Undo)
                            {
                                order.OrderStatus = (int)OrderStatus.Delete;
                                //var account = db.CashAccounts.Find(order.InMoneyAccountId);
                                //var vari = order.InMoneyAmount;
                                //var preAmount = account.Amount;
                                //account.Amount -= vari;
                                //account.OriginalAmount = preAmount;
                                //account.UpdateTime = DateTime.Now;
                                //var log = new CashAccountLog()
                                //{
                                //    OriginalAmount = preAmount,
                                //    VariableAmount = -vari,
                                //    MakerId = (int)order.MakerId,
                                //    MakerTime = DateTime.Now,
                                //    CashAccountId = account.Id,
                                //    CurrentAmount = account.Amount,
                                //    CreateTime = DateTime.Now,
                                //    LoginId = LoginInfo.GetLoginInfo().UserId,
                                //    Source = "销售单作废退款",
                                //    RelatedObject = order.OrderNo,
                                //    Remark = order.Remark
                                //};
                                //db.CashAccountLogs.Add(log);
                                var result = db.SaveChanges();
                                if (result > 0)
                                {
                                    db.SaveChanges();
                                    MessageBox.Show("作废订单成功！单号：" + order.OrderNo);
                                    searchBtn_Click(null, null);
                                }
                                else
                                    MessageBox.Show("作废订单失败！");
                            }
                            else
                            {
                                MessageBox.Show("作废订单失败！");
                            }
                        }
                    }

                }
                else
                {
                    MessageBox.Show("请选择行！");
                }
            }
            else
            {
                MessageBox.Show("请选择行！");
            }
        }

        private void dataGdv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               dataGdv.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGdv.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGdv.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void exportBtn_Click(object sender, EventArgs e)
        {
            Helper.ExportDgv(dataGdv, "销售单列表");
        }

        private void ReturnBtn_Click(object sender, EventArgs e)
        {
            var isSel = dataGdv.CurrentRow == null ? false : dataGdv.CurrentRow.Selected;
            if (isSel)
            {
                var rowIndex = dataGdv.CurrentRow.Index;
                if (rowIndex >= 0)
                {
                    var dr = MessageBox.Show("确定要退该订单吗？", "操作提示", MessageBoxButtons.OKCancel);
                    if (dr == DialogResult.OK)
                    {
                        if (dataGdv.CurrentRow.Cells["OrderNo"] != null)
                        {
                            var orderNo = dataGdv.CurrentRow.Cells["OrderNo"].Value.ToString();
                            var order = db.SaleOrders.FirstOrDefault(o => o.OrderNo == orderNo);
                            if (order == null)
                            {
                                MessageBox.Show("订单不存在！");
                                return;
                            }
                            if (order.OrderStatus != (int)OrderStatus.Checked)
                            {
                                MessageBox.Show("非已审核订单不能退！");
                                return;
                            }
                            order.OrderStatus = (int)OrderStatus.Returned;

                            //TODO  生成退货单


                            //var account = db.CashAccounts.Find(order.InMoneyAccountId);
                            //var vari = order.InMoneyAmount;
                            //var preAmount = account.Amount;
                            //account.Amount -= vari;
                            //account.OriginalAmount = preAmount;
                            //account.UpdateTime = DateTime.Now;
                            //var log = new CashAccountLog()
                            //{
                            //    OriginalAmount = preAmount,
                            //    VariableAmount = -vari,
                            //    MakerId = (int)order.MakerId,
                            //    MakerTime = DateTime.Now,
                            //    CashAccountId = account.Id,
                            //    CurrentAmount = account.Amount,
                            //    CreateTime = DateTime.Now,
                            //    LoginId = LoginInfo.GetLoginInfo().UserId,
                            //    Source = "销售单作废退款",
                            //    RelatedObject = order.OrderNo,
                            //    Remark = order.Remark
                            //};
                            //db.CashAccountLogs.Add(log);
                            var result = db.SaveChanges();
                            if (result > 0)
                            {
                                db.SaveChanges();
                                MessageBox.Show("作废订单成功！单号：" + order.OrderNo);
                                searchBtn_Click(null, null);
                            }
                            else
                                MessageBox.Show("作废订单失败！");

                        }
                    }

                }
                else
                {
                    MessageBox.Show("请选择行！");
                }
            }
            else
            {
                MessageBox.Show("请选择行！");
            }
        }

        private void CompanyNameTxt_TextChanged(object sender, EventArgs e)
        {

        }
    }
    public class DataItemStatus
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
